#!/bin/bash

dir="$(dirname "$0")"

DEPS="$dir/data/dependencies.list"


# Check if command failed, if true abort
function check_fail {
	EXITSTATUS=$1
	if [[ $EXITSTATUS != 0 ]]; then
		show_error "Something may have went wrong during the last command. Returning."
		sleep 3s && main
	fi
}

# Check for and install required packages for this script set.
function check_dependencies {
	show_info "Checking dependencies..."
	for package in $(cat $DEPS)
	do 
	PKGCHECK=$(dpkg-query -W --showformat='${Status}\n' $package|grep "install ok installed")
	if [ "" == "$PKGCHECK" ]; then
		show_info $NAME 'is not installed. Proceeding'
		show_info "This script requires '$package' and it is not present on your system."
		show_question 'Would you like to install it to continue? (Y)es, (N)o : ' && read REPLY
		echo ''
		case $REPLY in
		# Positive action
		[Yy]* ) 
			show_warning 'Requires root privileges'
			sudo apt-get -y install $package
			# Failure check
			check_fail
			show_success "Package '$package' installed. Proceeding."
			;;
		# Negative action
		[Nn]* )
			show_info "Exiting..."
			exit 99
			;;
		# Error
		* )
			show_error '\aSorry, try again.' && check
			;;
		esac
	else
		show_success "Dependency '$package' is installed."
	fi
	done
	show_info "Proceeding."
}